codedata <-
function(dd, tblname, dct=datadic, dateformat="%m/%d/%Y"){
    require(Hmisc)
    dct <- dct[dct$TBLNAME==toupper(tblname),]
    dct$CODE <- as.character(dct$CODE)
    fldnames = intersect(as.character(colnames(dd)), dct[,"FLDNAME"])
    fldnames = fldnames[!fldnames%in%c("ID","RID","PTID","PT_ID","SITE_ID")]
    for(fldname in fldnames){
        code = dct[dct$FLDNAME==toupper(fldname),"CODE"]
        type = dct[dct$FLDNAME==toupper(fldname),"TYPE"]
        if(!is.na(code)&grepl("=", code)){
          code = unlist(strsplit(as.character(code),";"))
          code = lapply(code,strsplit,"=")
          levels = gsub(" ", "", unlist(lapply(code,function(x) x[[1]][1])))
          labels = unlist(lapply(code,function(x) x[[1]][2]))
          dd[,fldname]=factor(as.character(dd[,fldname]),levels=levels,labels=labels)
        }else if( (!is.na(type)&type=="D") ){
          dd[,fldname] = as.character(dd[,fldname])
          # replace missing day with 15th
          dd[,fldname] <- gsub("/--/", "/15/", dd[,fldname])        
          # replace missing month with July
          dd[,fldname] <- gsub("--/", "07/", dd[,fldname])
          dd[,fldname] <- as.Date(dd[,fldname],  format=dateformat)
        }
        labels <- as.character(dct[dct$FLDNAME==toupper(fldname),c("TEXT","UNIT")])
        if(!is.na(labels[1])&labels[1]!="")
        label(dd[,fldname]) <- labels[1]
        if(!is.na(labels[2])&labels[2]!="")
        units(dd[,fldname]) <- labels[2]
    }
    dd
  }

